using UnityEngine;

namespace IQIGame.Onigao.GamePlay
{
    public enum AnimSwitchResetType
    {
        None,
        SpeedGreatZero,
    }

    /// <summary>
    /// 动画自动切换组件
    /// 使用示例：闲置多长时间自动切换到休闲待机动作
    /// </summary>
    public class AnimAutoSwtichTrigger : StateMachineBehaviour
    {
        [SerializeField]
        public bool autoSwitch;
        [SerializeField]
        public string autoTriggerName;
        [SerializeField]
        public Vector2 autoSwitchInterval;

        [SerializeField]
        public AnimSwitchResetType resetType;
        public string resetParameterName;

        private float _nextTimer;
        private float _nextSwitchTime;
        private bool _startSwitch;

        public bool enterState { private set; get; } = false;

        public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
        {
            enterState = true;
            if (autoSwitch)
            {
                _startSwitch = true;
                RandomNextSwitchTime();
            }
        }

        private void RandomNextSwitchTime()
        {
            _nextTimer = 0;
            _nextSwitchTime = Random.Range(autoSwitchInterval.x, autoSwitchInterval.y);
        }

        public override void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
        {
            if (!_startSwitch)
            {
                return;
            }
            bool needUpdateTimer = true;
            switch (resetType)
            {
                case AnimSwitchResetType.SpeedGreatZero:
                    var speed = animator.GetFloat(resetParameterName);
                    //速度大于一定程度的时候，重置计时器
                    if (Mathf.Abs(speed) >= 1e-3)
                    {
                        _nextTimer = 0;
                        needUpdateTimer = false;
                    }
                    break;
            }

            if (needUpdateTimer)
            {
                _nextTimer += Time.deltaTime;
            }

            if (_nextTimer >= _nextSwitchTime)
            {
                animator.SetTrigger(autoTriggerName);
                _startSwitch = false;
            }
        }

        public override void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
        {
            enterState = false;
            _startSwitch = false;
        }

    }
}
